import { App } from "vue";
import { createRouter, createWebHistory } from "vue-router"
import { baseRouters, layoutRouter, NotFoundRouter } from "./routers"
import { useNProgress } from '@vueuse/integrations/useNProgress'
import {getToken} from "@/utils/userData"
import {AppStore} from "@store/app"
import {sendUserInfo} from "@/views/loginSetup"

const NProgress = useNProgress()

const NProgressToggle = () => {
  NProgress.isLoading.value = !NProgress.isLoading.value
}
const whites = ['/login', '/register', '/error']

export const useRouter = (app: App) => {
  const router = createRouter({
    history: createWebHistory('/'),
    routes: baseRouters
  })
  app.use(router)
  const store = AppStore()
  router.beforeEach(async (to, from, next) => {
    NProgressToggle()
    if(whites.includes(to.path)){
      next()
    }else{
      const token = getToken()
      if(!token){
        next({path: whites[0]})
      } else {
        if(!Object.keys(store.commonDict).length) {
          await store.updateCommonDict()
        }

        const hasRouter = store.addRouter.length > 0
        if(!hasRouter){
          try {
            const {data} = await sendUserInfo(token)
            store.updateAddRoute(data.perPageList)
            router.addRoute({...layoutRouter, redirect: store.addRouter[0].path, children: store.addRouter})
            router.addRoute(NotFoundRouter)
            next({path: store.addRouter[0].path})
          } catch (error) {
            store.userLogout(() => {
              next({path: whites[0]})
            })
          }
        }else{
          next()
        }
      }
    }
  })

  router.afterEach(() => {
    NProgressToggle()
  })
}